<?php

namespace App\Http\Controllers\Guard\Dev;

use App\Http\Controllers\Common\GuardController;
use App\Models\Dev\CoalArea;
use Illuminate\Http\Request;

class AreaController extends GuardController{


    public function __construct() {
        $this->instance = new CoalArea();
    }

    public function lst(Request $request) {

        if($request->has('tree')){
            $records = CoalArea::where('pid',0)->with('children:id,name,pid')->get(['id','name','pid']);
            $this->handleChildren($records);
            return responseSuccess($records->toArray());
        }
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',50);
        $conditions = $request->input();
        $records = $this->instance->getLst($conditions)
            ->with('getBelong:id,name,pid')
            ->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());
    }

    public function getAreaMap(Request $request){
        $level = $request->input('level');
        $records = $this->instance->where(compact('level'))->with('getBelong')->get(['name','id','level','pid']);
        if($level==2){
            foreach ($records as $record) {
                if(!empty($record->getBelong))
                    $record->name = $record->getBelong->name.'--'.$record->name;
            }
        }

        return responseSuccess($records->toArray());
    }

    public function add(Request $request) {
        $info = $request->input();
        $this->validate($request, [
            'name'=>'required'
        ],[],[
            'name'=>'名称'
        ]);
        $record = $this->instance->updateOrCreate(['id'=>$info['id']??0],$info);
        return responseSuccess($record->toArray(),1);
    }
}
